<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "MapView",
  data() {
    return {
      map: null,
      points: [],
      districtCenters: {
        北京市: { center: '116.405285,39.904989' },
        上海市: { center: '121.473701,31.230416' },
        武汉市: { center: '114.305393,30.593099' },
        广州市: { center: '113.264385,23.129112' },
        // 其他地区中心点...
      },
    };
  },
  created() {
    this.fetchEquipmentList();
  },
  mounted() {
    this.loadScripts().then(() => {
      this.initAMap();
    });
  },
  methods: {
    loadScripts() {
      return new Promise((resolve, reject) => {
        const communityScript = document.createElement("script");
        communityScript.src = "https://a.amap.com/jsapi_demos/static/data/community.js";
        document.body.appendChild(communityScript);

        const districtScript = document.createElement("script");
        districtScript.src = "https://a.amap.com/jsapi_demos/static/data/district.js";
        document.body.appendChild(districtScript);

        const amapScript = document.createElement("script");
        amapScript.src = "https://webapi.amap.com/maps?v=2.0&key=608d75903d29ad471362f8c58c550daf&plugin=AMap.IndexCluster";
        document.body.appendChild(amapScript);

        amapScript.onload = () => {
          resolve();
        };
        amapScript.onerror = (e) => {
          reject(e);
        };
      });
    },
    fetchEquipmentList() {
      // 模拟获取设备列表的API请求
      this.points = [
        { lng: 116.405285, lat: 39.904989 },
        { lng: 121.473701, lat: 31.230416 },
        // 其他点...
      ];
      this.initMarkers();
    },
    initAMap() {
      AMapLoader.load({
        key: "your-amap-key", // 申请好的Web端开发者Key
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.IndexCluster"], // 需要使用的插件列表
      })
      .then((AMap) => {
        this.map = new AMap.Map("container", {
          zoom: 9,
          animateEnable: true,
          mapStyle: "amap://styles/grey",
        });

        this.initCluster(AMap);
      })
      .catch((e) => {
        console.log(e);
      });
    },
    initCluster(AMap) {
      const clusterIndexSet = {
        city: {
          minZoom: 2,
          maxZoom: 10,
        },
        district: {
          minZoom: 10,
          maxZoom: 12,
        },
        area: {
          minZoom: 12,
          maxZoom: 15,
        },
        community: {
          minZoom: 15,
          maxZoom: 22,
        },
      };

      const cluster = new AMap.IndexCluster(this.map, this.points, {
        renderClusterMarker: this.renderClusterMarker,
        clusterIndexSet: clusterIndexSet,
      });
    },
    renderClusterMarker(context) {
      const styleObj = this.getStyle(context);
      const div = document.createElement('div');
      div.className = 'amap-cluster';
      div.style.backgroundColor = styleObj.bgColor;
      div.style.width = styleObj.size + 'px';
      div.style.height = styleObj.size + 'px';
      div.style.border = 'solid 1px ' + styleObj.borderColor;
      div.style.borderRadius = styleObj.size + 'px';
      div.innerHTML = styleObj.text;
      div.style.color = styleObj.color;
      div.style.textAlign = styleObj.textAlign;
      div.style.boxShadow = styleObj.boxShadow;
      context.marker.setContent(div);
      const position = this.getPosition(context);
      if (position) {
        context.marker.setPosition(position);
      }
      context.marker.setAnchor('center');
    },
    getStyle(context) {
      const color = [
        '8,60,156',
        '66,130,198',
        '107,174,214',
        '78,200,211',
      ];
      const indexs = ['city', 'district', 'area', 'community'];
      const i = indexs.indexOf(context.index['mainKey']);
      const text = context.clusterData[0][context.index['mainKey']];
      const size = Math.round(30 + Math.pow(context.count / this.points.length, 1 / 5) * 70);
      const extra = '<span class="showCount">' + context.count + '个</span>';
      const styleText = '<span class="showName">' + text + '</span>' + extra;

      return {
        bgColor: 'rgba(' + color[i] + ',.8)',
        borderColor: 'rgba(' + color[i] + ',1)',
        text: styleText,
        size: size,
        index: i,
        color: '#ffffff',
        textAlign: 'center',
        boxShadow: '0px 0px 5px rgba(0,0,0,0.8)',
      };
    },
    getPosition(context) {
      const key = context.index.mainKey;
      const dataItem = context.clusterData && context.clusterData[0];
      const districtName = dataItem[key];
      if (!this.districtCenters[districtName]) {
        return null;
      }
      const center = this.districtCenters[districtName].center.split(',');
      return new AMap.LngLat(center[0], center[1]);
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
.amap-cluster {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}
.showName {
  font-size: 14px;
}
.showCount, .showName {
  display: block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
}
</style>
